package com.celesea.configuration.web;

import com.alibaba.fastjson.JSON;
import com.celesea.framework.api.HttpKit;
import com.celesea.framework.api.Tip;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

//@ControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public Tip<Object> validExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e) throws Exception {
        logger.info(JSON.toJSONString(req.getParameterMap()));
        logger.error(e.getMessage(), e);
        return HttpKit.failed(e.getMessage());
    }

    @ExceptionHandler(value = {RuntimeException.class})
    @ResponseBody
    public Tip<Object> runtimeExceptionHandler(HttpServletRequest req, RuntimeException e) throws Exception {
        logger.info(JSON.toJSONString(req.getParameterMap()));
        logger.error(e.getMessage(), e);
        return HttpKit.failed(e.getMessage());
    }

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public Tip<Object> exceptionHandler(HttpServletRequest req, Exception e) throws Exception {
        logger.info(JSON.toJSONString(req.getParameterMap()));
        logger.error(e.getMessage(), e);
        return HttpKit.failed(e.getMessage());
    }


    @ExceptionHandler(BindException.class)
	@ResponseBody
	public Tip<List<String>> bindExceptionHandle(BindException e) {
		return processBindResult(e.getBindingResult());
	}
	
	private Tip<List<String>> processBindResult(BindingResult result) {
		List<String> list = new ArrayList<>();
		for(FieldError fieldError : result.getFieldErrors()) {
			String error = String.format("%1$s%2$s", fieldError.getField(),
                    fieldError.getDefaultMessage());
			list.add(error);
		}
		return HttpKit.failed(StringUtils.join(list, ","));
	}

}
